#include <Box2D/Common/b2Math.h>
#include "./entity.h"

Entity::Entity()
{
    text = 0;
    phy = 0;
    type = EET_ENTITY;
    path = "empty";
    env = 0;
}
Entity::Entity(sleek::core::engine::engine *engine, sleek::core::os::stringc p)
{
    text = 0;
    phy = 0;
    type = EET_ENTITY;
    path = p;
    env = new sleek::node::billboard::Billboard(engine);

    if(sleek::texture::IsTextureFormatBmp(p)) text = sleek::texture::LoadTextureFromBmp(p);
    else if(sleek::texture::IsTextureFormatPng(p)) text = sleek::texture::LoadTextureFromPng(p);
    else if(sleek::texture::IsTextureFormatTga(p)) text = sleek::texture::LoadTextureFromTga(p);
    else if(sleek::texture::IsTextureFormatJpg(p)) text = sleek::texture::LoadTextureFromJpg(p);
    else printf("No switable format for %s\n", p.c_str());

    env->getMaterial()->setTexture(0, text);
}
Entity::~Entity()
{
}

sleek::texture::texture* Entity::getTexture()
{
    return text;
}

void Entity::setPosition(sleek::core::math::vector2df pos)
{
    b2Vec2 newpos(pos.width, pos.height);
    phy->SetTransform(newpos, phy->GetAngle());
    update(b2Vec2(pos.width, pos.height), phy->GetAngle());
}

void Entity::setRotation(float r)
{
    phy->SetTransform(phy->GetPosition(), r/180*sleek::core::PI);
    update(phy->GetPosition(), r);
}

void Entity::update(b2Vec2 b, float r)
{
    env->setPosition(sleek::core::math::vector3df(b.x, b.y, env->getPosition().z));
    sleek::core::math::vector3df nrot = env->getRotation();
        nrot.z = r;
    env->setRotation(nrot);
}

Json::Value Entity::save()
{
    b2dJson json;
    Json::Value save = json.b2j(phy);
    save["entity"] = type;
    save["zorder"] = env->getPosition().z;
    save["scale_x"] = env->getScale().x;
    save["scale_y"] = env->getScale().y;
    save["scale_z"] = env->getScale().z;
    save["path"] = path.c_str();
    return save;
}
